import { ipcRenderer, contextBridge } from 'electron'

import { uptime } from 'node:os'
import fs from 'node:fs'
import path from 'node:path'
import { randomUUID } from 'node:crypto'

const VITE_DEV_SERVER_URL = process.env['VITE_DEV_SERVER_URL']
const INSERT_JS_PATH = path.join(VITE_DEV_SERVER_URL ? process.env.VITE_PUBLIC : process.resourcesPath, 'insert.js')

// --------- Expose some API to the Renderer process ---------
contextBridge.exposeInMainWorld('ipcRenderer', {
  on(...args: Parameters<typeof ipcRenderer.on>) {
    const [channel, listener] = args
    return ipcRenderer.on(channel, (event, ...args) => listener(event, ...args))
  },
  off(...args: Parameters<typeof ipcRenderer.off>) {
    const [channel, ...omit] = args
    return ipcRenderer.off(channel, ...omit)
  },
  send(...args: Parameters<typeof ipcRenderer.send>) {
    const [channel, ...omit] = args
    return ipcRenderer.send(channel, ...omit)
  },
  invoke(...args: Parameters<typeof ipcRenderer.invoke>) {
    const [channel, ...omit] = args
    return ipcRenderer.invoke(channel, ...omit)
  },

  // You can expose other APTs you need here.
  // ...
})

contextBridge.exposeInMainWorld('electronIpc', {
  uptime,
  randomUUID,
  insertJs: fs.existsSync(INSERT_JS_PATH) ? fs.readFileSync(INSERT_JS_PATH, 'utf8') : 'alert("网页全屏脚本已丢失")'
})
